﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WS.EKA.Business.Model;
using System.Data.Common;
using Oracle.DataAccess.Client;

namespace WS.EKA.Business.Dal
{
    public class ITAnnouncementAccess
    {
        static IDB DBHelper = DBFactory.CreateBODB();
        #region OnDuty
        public static void AddOnDuty(OnDuty obj)
        {
            Add<OnDuty>(obj, "tb_Onduty");
        }

        public static List<OnDuty> GetLatestOnDuty()
        {
            return Get<OnDuty>("tb_Onduty", 1);
        }

        #endregion

        #region  LatestImportantTask

        public static void AddLatestImportantTask(LatestImportantTask obj)
        {
            Add<LatestImportantTask>(obj, "tb_LatestImportantTask");
        }

        public static List<LatestImportantTask> GetLatestImportantTask(int topCount)
        {
            return Get<LatestImportantTask>("tb_LatestImportantTask", topCount);
        }

        #endregion

        #region  Announcement

        public static void AddAnnounceMent(AnnounceMent obj)
        {
            Add<AnnounceMent>(obj, "tb_AnnounceMent");
        }

        public static List<AnnounceMent> GetAnnounceMent(int topCount)
        {
            return Get<AnnounceMent>("tb_AnnounceMent", topCount);
        }

        #endregion

        private static void Add<T>(T obj, string tableName) where T : ITAnnounceMent
        {
            var parameters = new List<OracleParameter>();
            parameters.Add(new OracleParameter("Content", obj.Content));
            parameters.Add(new OracleParameter("CreateTime", obj.CreateTime));
            parameters.Add(new OracleParameter("CreateBy", obj.CreateBy));
            parameters.Add(new OracleParameter("Note", obj.Note));
            DBHelper.ExecuteNonQuery("INSERT INTO " + tableName + "(Content,CreateTime,CreateBy,Note) values(:Content,:CreateTime,:CreateBy,:Note)", parameters.ToArray());

        }

        private static List<T> Get<T>(string tableName, int topCount) where T : ITAnnounceMent, new()
        {
            var result = new List<T>();
            var parameters = new OracleParameter[1];
            parameters[0] = new OracleParameter("Num", topCount);

            using (var dataReader = DBHelper.ExecuteReader(" SELECT ROW_.*, ROWNUM ROWNUM_ FROM (SELECT Content,CreateTime FROM " + tableName + " ORDER by CreateTime desc ) ROW_ WHERE ROWNUM <=:Num", parameters))
            {
                while (dataReader.Read())
                {
                    result.Add(new T()
                    {
                        Content = dataReader[0].ToString(),
                        CreateTime = Convert.ToDateTime(dataReader[1]),
                    });
                }
            }
            return result;
        }
    }
}
